from django.urls import reverse
from django.conf import settings
from django.contrib.auth import login
from django.http import JsonResponse, HttpResponseForbidden
from django.shortcuts import render, redirect
from django.views import View
from QQLoginTool.QQtool import OAuthQQ
from django_redis import get_redis_connection
from apps.oauth.utils import SecretOauth
from apps.users.models import User
from meiduo_mall.settings.dev import logger
from apps.oauth.models import OAuthQQUser
import re


# 回调网站   code-->token-->openid
class QQAuthView(View):
    def get(self, request):
        code = request.GET.get('code')
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                    redirect_uri=settings.QQ_REDIRECT_URI, state=next)

        # 2.使用code--->token
        token = oauth.get_access_token(code)
        # 使用token--->openid
        openid = oauth.get_open_id(token)
        # 判断openid 是否绑定了

        try:
            oauth_user = OAuthQQUser.objects.get(openid=openid)
        except Exception as e:
            logger.error(e)
            # 没有绑定 跳转到绑定页面
            context = {'openid': openid}
            context = SecretOauth().dumps(context)
            # context = {'openid': context}
            return render(request, 'oauth_callback.html', context)

        else:
            # 绑定了-保持登录状态->重定向到首页-->设置cookie username
            qq_user = oauth_user.user
            login(request, qq_user)
            response = redirect(reverse('contents:index'))
            response.set_cookie('username', qq_user.username, max_age=3600 * 24 * 15)
            return response


    def post(self, request):
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('password')
        sms_code_client = request.POST.get('sms_code')
        openid = request.POST.get('openid')

        # 校验参数
        # 判断参数是否齐全
        if not all([mobile, pwd, sms_code_client]):
            return HttpResponseForbidden('缺少必传参数')
        # 判断手机号是否合法
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return HttpResponseForbidden('请输入正确的手机号码')
        # 判断密码是否合格
        if not re.match(r'^[0-9A-Za-z]{8,20}$', pwd):
            return HttpResponseForbidden('请输入8-20位的密码')
        # 判断短信验证码是否一致
        redis_conn = get_redis_connection('sms_code')
        sms_code_server = redis_conn.get('sms_%s' % mobile)
        if sms_code_server is None:
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '无效的短信验证码'})
        if sms_code_client != sms_code_server.decode():
            return render(request, 'oauth_callback.html', {'sms_code_errmsg': '输入短信验证码有误'})
        # 解密出openid 再判断openid是否有效
        openid = SecretOauth().loads(openid).get('openid')

        if not openid:
            return render(request, 'oauth_callback.html', {'openid_errmsg': '无效的openid'})
        # .判断用户是否存在 存在 user; 不存在新建user
        try:
            user = User.objects.get(mobile=mobile)
        except Exception as e:
            # 不存在 新建user
            user = User.objects.create(username=mobile, password=pwd, mobile=mobile)
        else:
            # 密码不正确
            if not user.check_password(pwd):
                return render(request, 'oauth_callback.html', {'account_errmsg': '用户名或密码错误'})

        # 将用户绑定openid
        try:
            OAuthQQUser.objects.create(openid=openid, user=user)
        except Exception as e:
            return render(request, 'oauth_callback.html', {'qq_login_errmsg': 'QQ登录失败'})
        # 保持登入状态
        login(request, user)
        response = redirect(reverse("contents:index"))
        # 等用户登录成功  合并 cookie和 redis的购物车数据
        from apps.carts.utils import merge_cart_cookie_to_redis
        merge_cart_cookie_to_redis(request, user, response)
        response.set_cookie('username', user.username, max_age=24 * 15 * 3600)
        return response

class QQAuthURLView(View):
    def get(self, request):
        # 创建OAuthQQ对象
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID, client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI, state=next)
        login_url = oauth.get_qq_url()
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'login_url': login_url})